package me.linczh.bank.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import me.linczh.bank.bean.AccountBean;
import me.linczh.bank.bean.enums.AccountType;
import me.linczh.bank.dao.AccountDao;
import me.linczh.framework.persiste.FileStoreHolder;
import me.linczh.framework.persiste.IdGenerator;
import me.linczh.framework.query.Query;

public class FileAccountDao implements AccountDao {	
	
	@Override
	public AccountBean create(AccountBean _account) {
		// TODO Auto-generated method stub
		_account.setCreatetime(new Date());
		String nextId = IdGenerator.nextId(_account);
		if (nextId != null) {
			_account.setAccount(nextId);
			FileStoreHolder.getAccountRecords().put(nextId, _account);
			// write to file
			FileStoreHolder.flushAccountRecords();
			return _account;
		}
		return null;
	}

	@Override
	public boolean update(AccountBean _account) {
		// TODO Auto-generated method stub
		Map<String, AccountBean> map = FileStoreHolder.getAccountRecords();
		if (map.containsKey(_account.getAccount())) {
			map.put(_account.getAccount(), _account);
			// write to file
			FileStoreHolder.flushAccountRecords();
			return true;
		}
		return false;
	}
	

	@Override
	public AccountBean findById(String accoundID) {
		// TODO Auto-generated method stub
		Map<String, AccountBean> map = FileStoreHolder.getAccountRecords();
		if (map.containsKey(accoundID)) return map.get(accoundID);
		return null;
	}

	@Override
	public List<AccountBean> query(Query<AccountBean> query) {
		// TODO Auto-generated method stub
		List<AccountBean> list = new ArrayList<AccountBean>();
		Map<String, AccountBean> map = FileStoreHolder.getAccountRecords();
		for (String s : map.keySet()) {
			AccountBean bean = map.get(s);
			if (query.matched(bean)) list.add(bean);
		}
		return list;
	}
	
	@Override
	public boolean delete(AccountBean _account) {
		// TODO Auto-generated method stub
		Map<String, AccountBean> map = FileStoreHolder.getAccountRecords();
		if (map.containsKey(_account.getAccount())) {
			map.remove(_account.getAccount());
			if (_account.getAccounttype() == AccountType.PERSONAL_VIP) {
				FileStoreHolder.getStatisticRecords().remove(_account.getAccount());
				FileStoreHolder.flushStatisticRecords();
			}
			// write to file
			FileStoreHolder.flushAccountRecords();
			return true;
		}
		return false;
	}
}
